package org.example.manySheetExcel;

/**
 * @author 望轩
 * @createDate 2025/8/21 11:33
 */

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import lombok.Data;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 自定义数据监听器（处理数据校验）
 */
@Data
public class RegionDataListener implements ReadListener<RegionDTO> {
    private final List<RegionDTO> validDataList = new ArrayList<>();
    private final List<RegionDTO> invalidDataList = new ArrayList<>();
    private final Validator validator;

    public RegionDataListener() {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        this.validator = factory.getValidator();
    }

    @Override
    public void invoke(RegionDTO data, AnalysisContext context) {
        //把行号假如到RegionDTO对象中的rowNum属性中
        data.setRowNum(context.readRowHolder().getRowIndex());

        // 执行数据校验
        Set<ConstraintViolation<RegionDTO>> violations = validator.validate(data);

        if (violations.isEmpty()) {
            validDataList.add(data);
        } else {
            // 收集错误信息
            StringBuilder errorMsg = new StringBuilder();
            violations.forEach(v -> errorMsg.append(v.getMessage()).append(";"));
            data.setErrorMsg(errorMsg.toString());
            invalidDataList.add(data);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 所有数据解析完成后的操作（如批量保存）
    }

}
